<?php

/**
 * ActiveRecord class
 *
 * @author Julot
 * @since Thursday, April 12, 2012. 01:39 PM
 */
class ActiveRecord extends CActiveRecord {

	public function init() {
		parent::init();
		$now = date('Y-m-d H:i:s');
		$this->createdAt = $now;
		$this->updatedAt = $now;
	}
	
	public function rules() {
		$rules = array();
		$rules[] = array(
			array('createdAt', 'updatedAt'),
			'date',
			'format'=>'yyyy-MM-dd HH:mm:ss',
			'allowEmpty'=>false,
		);
		return $rules;
	}

	public function behaviors() {
		$behaviors = array();
		$behaviors['timestamp'] = array(
			'class'=>'zii.behaviors.CTimestampBehavior',
			'createAttribute'=>null,
			'updateAttribute'=>'updatedAt',
			'setUpdateOnCreate'=>true,
			'timestampExpression'=>"date('Y-m-d H:i:s')",
		);
		$behaviors['dynamicData'] = array(
			'class'=>'DynamicDataProviderBehavior',
		);
		return $behaviors;
	}
	
	public function getMenu($action, $toolbar=false) {
		$name = get_class($this);
		$name = strtolower($name{0}) . substr($name, 1);
		$user = Yii::app()->user;
		$tool = Yii::app()->request->baseUrl . '/images/toolbars';
		$menu = array();
		
		$label = $toolbar ? "<img src=\"$tool/magnifier-left.png\" />" : "View";
		$menu[] = array(
			'label'=>$label,
			'url'=>array("/$name/view", 'id'=>$this->id),
			'visible'=>$action != 'view',
			'linkOptions'=>array('title'=>'View'),
		);
		
		$label = $toolbar ? "<img src=\"$tool/pencil.png\" />" : "Update";
		$menu[] = array(
			'label'=>$label,
			'url'=>array("/$name/update", 'id'=>$this->id),
			'visible'=>$action != 'update',
			'linkOptions'=>array('title'=>'Update'),
		);
		
		$label = $toolbar ? "<img src=\"$tool/cross-script.png\" />" : "Delete";
		$menu[] = array(
			'label'=>$label,
			'url'=>array("/$name/delete", 'id'=>$this->id),
			'linkOptions'=>array(
				'submit'=>array("/$name/delete", 'id'=>$this->id),
				'confirm'=>'Are you sure you want to delete this item?',
				'title'=>'Delete',
			)
		);
		
		return $menu;
	}
	
	public function getUrl($attribute=null) {
		if (!$attribute) {
			$attributes = array('name', 'code', 'id');
			foreach ($attributes as $attribute) {
				if (isset($this->$attribute)) {
					break;
				}
			}
		}
		$caption = $this->$attribute;
		$class = get_class($this);
		$first = strtolower($class[0]);
		$rest = substr($class, 1);
		$url = array(
			"/{$first}{$rest}/view",
			'id'=>$this->id,
		);
		$htmlOptions = array(
		);
		$url = CHtml::normalizeUrl($url);
		return CHtml::link($caption, $url, $htmlOptions);
	}
	
	public function resetPk() {
		$name = $this->tableName();
		$sql = "ALTER TABLE $name AUTO_INCREMENT = 1;";
		$command = Yii::app()->db->createCommand($sql);
		$command->execute();
	}
	
}

